package Controllers;


import java.rmi.RemoteException;
import java.util.List;

import Models.BoardModel2D;
import Models.GameModel;
import Models.Player;
import Models.Point2D;
import Models.StandardGameModel;

public class GameController implements GameControllerInterface {
	
	public static GameModel getNew(Player player1, Player player2) {
		BoardModel2D board = BoardController.getNew();
		BoardControllerInterface boardController = new BoardController();
		
		try {
			
			boardController.resetStartingPotition(board, player1, player2);
			
		} catch (RemoteException e) {
			
			e.printStackTrace();
		}
		
		GameModel newGame = new StandardGameModel(board, player1, player2);
		
		return newGame;
	}
	
	@Override
	public void nextTurn(GameModel gameModel) {
		List<Player> players = gameModel.getPlayers();
		
		int indexOfCurrent = players.indexOf(gameModel.getCurrentPlayer());
		
		
		Player nextPlayer;
		
		if(players.size() > indexOfCurrent + 1)
			nextPlayer = players.get(indexOfCurrent + 1);
		else
			nextPlayer = players.get(0);
			
		
		
		
		gameModel.setCurrentPlayer(nextPlayer);
		
	}

	@Override
	public boolean movePiece(Point2D startPosition, Point2D endPosition,GameModel gameModel) throws RemoteException {
		if (gameModel.getBoard().getPiece(startPosition) != null) {
			if (gameModel.getBoard().getPiece(startPosition).getPlayer() == gameModel.getCurrentPlayer()) {
				if (gameModel.getBoard().canMoveNotify(startPosition, endPosition, gameModel.getBoard())) {
					nextTurn(gameModel);
					return true;
				}
		
			}
		}
		return false;
		
	}

}
